package top.huxy.boot.controller.admin;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;
import org.springframework.web.bind.annotation.*;
import top.huxy.boot.annotation.RequestRemake;
import top.huxy.boot.config.Constant;
import top.huxy.boot.model.entity.Admin;
import top.huxy.boot.model.vo.VOAdmin;
import top.huxy.boot.service.AdminService;
import top.huxy.boot.util.Assert;
import top.huxy.boot.util.StringUtils;
import top.huxy.boot.util.obj.Result;

import javax.servlet.http.HttpServletResponse;
import java.time.Duration;

/**
 * 管理员操作控制器
 */
@RestController
@RequestMapping("/admin/admin")
public class AdminController {

    RedisTemplate<String, Object> redisTemplate;

    AdminService adminService;

    public AdminController(RedisTemplate<String, Object> redisTemplate, AdminService adminService) {
        this.redisTemplate = redisTemplate;
        this.adminService = adminService;
    }

    @PostMapping("/login")
    @RequestRemake(value = "管理员登录", saveParams = false)
    public Result login(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            @RequestParam("yzm") String yzm,
            @CookieValue(name = Constant.ADMIN_TOKEN_NAME, required = false) String admin_token,
            HttpServletResponse response
    ) {
        //参数合法性判断
        Assert.assertTrue(!StringUtils.isEmpty(username, password, yzm), "缺少必要参数");

        VOAdmin admin = adminService.doLogin(username, password, yzm, admin_token);
        if (admin == null) {
            return Result.clientError("登录失败");
        }

        String token = admin.getToken();
        ResponseCookie responseCookie = ResponseCookie.from(Constant.ADMIN_TOKEN_NAME, token)
                .sameSite("None")
                .path("/")
                .maxAge(Duration.ofHours(24))
                .secure(true)
                .build();
        response.setHeader(HttpHeaders.SET_COOKIE, responseCookie.toString());
        return Result.success(admin, "登录成功");
    }

    @GetMapping("/autoLogin")
    @RequestRemake("管理员自动登录")
    public Result autoLogin(Admin admin, @CookieValue(Constant.ADMIN_TOKEN_NAME) String token) {
        VOAdmin voAdmin = new VOAdmin(admin);
        voAdmin.setToken(token);
        return Result.success(voAdmin);
    }
}
